package com.onstar.cn.weight.ptr;

import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;

/**
 * Created by Rengui Lu on 2016/9/20.
 */
public class FixedHVConflict {
    private ViewGroup mParent;
    private int mTouchSlop;
    private boolean isStopTracker = false;
    private int mLastRawX;
    private int mLastRawY;

    private View mHolder;
    private Context mContext;

    public FixedHVConflict(View mHolder){
        this.mHolder = mHolder;
        mContext = mHolder.getContext();
        if(null == mParent)
            mParent = (ViewGroup) mHolder.getParent();
        mTouchSlop = ViewConfiguration.get(mContext).getScaledTouchSlop() - 1;
    }

    public void dispatchTouchEvent(MotionEvent ev) {
        if(mParent == null){
            mParent = (ViewGroup) mHolder.getParent();
        }
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (mParent != null)
                    mParent.requestDisallowInterceptTouchEvent(true);
                mLastRawX = (int) ev.getRawX();
                mLastRawY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (!isStopTracker) {
                    int curX = (int) ev.getRawX();
                    int curY = (int) ev.getRawY();
                    int difX = Math.abs(curX - mLastRawX);
                    int difY =  Math.abs(curY - mLastRawY);
                    if (difX >= mTouchSlop || difY >= mTouchSlop) {
                        isStopTracker = true;
                        if(difX > difY){
                            if (mParent != null)
                                mParent.requestDisallowInterceptTouchEvent(true);
                        }else{
                            if (mParent != null)
                                mParent.requestDisallowInterceptTouchEvent(false);
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                if (mParent != null)
                    mParent.requestDisallowInterceptTouchEvent(false);
                isStopTracker = false;
                mLastRawX = mLastRawY = 0;
                break;
            default:
                break;
        }
    }
}
